let app = getApp()

// 获取云数据库引用
const db = wx.cloud.database()
const admin = db.collection('adminlist')
const MAX_LIMIT = 20
let id = ''
let phone = ''

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    phone: '',
    password: '',
    adminList: []
  },

  // 输入学号
  inputId: function (event) {
    id = event.detail
    this.setData({
      id: event.detail
    })
  },

  // 输入手机号
  inputPhone: function (event) {
    phone = event.detail
    this.setData({
      phone: event.detail
    })
  },

  recoverUn: function () {
    let that = this
    // 登陆获取用户信息
    if (id === '') {
      wx.showToast({
        title: '请输入学号',
        icon: 'error',
        mask: 'true',
        duration: 700
      })
    } else if (phone === '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'error',
        mask: 'true',
        duration: 700
      })
    } else {
      admin.count().then(async (res) => {
        let total = res.total
        // console.log(total);
        // 计算需分几次取
        const batchTimes = Math.ceil(total / MAX_LIMIT)
        // 承载所有读操作的 promise 的数组
        for (let i = 0; i < batchTimes; i++) {
          await admin.skip(i * MAX_LIMIT).limit(MAX_LIMIT)
            .get()
            .then(async (res) => {
              let newData = res.data
              let oldData = that.data.adminList
              that.setData({
                adminList: oldData.concat(newData)
              })
            })
        }
      })
        .then((res) => {
          let user = that.data.adminList
          let flag = false
          for (let i = 0; i < user.length; i++) { // 遍历数据库对象集合
            if (id === user[i].id) {
              flag = true // 学号存在
              const thisMsg = user[i]
              if (phone !== user[i].phone) { // 判断手机号是否匹配
                wx.showToast({
                  title: '手机号错误！',
                  icon: 'error',
                  mask: 'true',
                  duration: 700
                })
              } else {
                wx.showToast({
                  title: '获取中',
                  icon: 'loading',
                  mask: 'true',
                  duration: 500,
                  success: function () {
                  // 匹配成功 显示用户名
                    that.setData({
                      username: thisMsg.username
                    })
                  }
                })
              }
            }
          }
          if (!flag) {
            wx.showToast({
              title: '学号错误！',
              icon: 'error',
              duration: 700
            })
          }
        })
    }
  }

})